package com.sz.sjtb.util;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

@Component
public class AESEncryptUtils {
    public static String AES_DATA_SECURITY_KEY;
    private static final String AES_PKCS5P = "AES/ECB/PKCS5Padding";

    public AESEncryptUtils() {
    }

    @Value("${do1.dataencrypt-secret:jkl;POIU1234++==}")
    public void setAesDataSecurityKey(String secretKey) {
        AES_DATA_SECURITY_KEY = secretKey;
    }

    public static String encrypt(String str, String key) {
        try {
            if (str == null) {
                return null;
            } else {
                if (StringUtils.isEmpty(key)) {
                    key = AES_DATA_SECURITY_KEY;
                } else if (key.length() != 16) {
                    return null;
                }

                byte[] raw = key.getBytes("UTF-8");
                SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
                Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
                cipher.init(1, skeySpec);
                byte[] encrypted = cipher.doFinal(str.getBytes("UTF-8"));
                return (new BASE64Encoder()).encode(encrypted);
            }
        } catch (Exception var6) {
            return null;
        }
    }

    public static String decrypt(String str, String key) {
        try {
            if (str == null) {
                return null;
            } else {
                if (StringUtils.isEmpty(key)) {
                    key = AES_DATA_SECURITY_KEY;
                } else if (key.length() != 16) {
                    return null;
                }

                byte[] raw = key.getBytes("UTF-8");
                SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
                Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
                cipher.init(2, skeySpec);
                byte[] encrypted1 = (new BASE64Decoder()).decodeBuffer(str);

                try {
                    byte[] original = cipher.doFinal(encrypted1);
                    String originalString = new String(original, "UTF-8");
                    return originalString;
                } catch (Exception var8) {
                    return null;
                }
            }
        } catch (Exception var9) {
            return null;
        }
    }

    public static String encrypt(String str) {
        return encrypt(str, AES_DATA_SECURITY_KEY);
    }

    public static String decrypt(String str) {
        return decrypt(str, AES_DATA_SECURITY_KEY);
    }
}